// house_pkg/pages/locate/index.ts
import qqMap from '../../../utils/qqmap'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: '',
    houses: [],
    // title: '建材城西路9号'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.getLocation()
  },
  //获得定位
  async getLocation() {
    const {
      latitude,
      longitude
    } = await wx.getLocation()
    // console.log(longitude, latitude, 111);
    this.getAdress(longitude, latitude)
  },
  //重新定位
  async chooseLocation() {
    const {
      latitude,
      longitude
    } = await wx.chooseLocation()
    // console.log(longitude, latitude, 111);
    this.getAdress(longitude, latitude)
  },
  // 根据经纬度获取地址
  getAdress(longitude, latitude) {
    qqMap.reverseGeocoder({
      location: `${latitude},${longitude}`,
      success: (res) => {
        // console.log(res, 222);
        const {
          address
        } = res.result
        this.setData({
          address
        })
      }
    })
    qqMap.search({
      keyword: 'houses', //搜索关键词
      location: `${latitude},${longitude}`,
      page_size: 5,
      success: (res) => {
        // console.log(res, 444);
        const houses = res.data.map((item) => {
          console.log(houses, 2222);
          return {
            id: item.id,
            title: item.title,
            distance: item._distance
          }
        })
        this.setData({
          houses
        })
      },
      fail: () => {
        const arr = [{
            id: 1,
            title: '模拟小区1'
          },
          {
            id: 2,
            title: '模拟小区2'
          }
        ]
        this.setData({
          houses: arr
        })
      }
    })
  }
})